package com.zdyl.springboot_shiro.shiro.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.zdyl.springboot_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro的配置类
 * @author lenovo
 *
 */
@Configuration
public class ShiroConfig {

    /**
     * 创建ShiroFilterFactoryBean
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean  getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean() ;
      //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /**
         * Shiro内置过滤器,可以实现权限相关的拦截器
         *     常用的过滤器
         *           anon: 无需认证才可以访问
         *           authc: 必须认证才可以访问
         *           user: 如果使用rememberMe的功能可以直接访问
         *           perms: 该资源必须得到资源权限才可以访问
         *           role: 该资源必须得到角色权限才可以访问
         *
         */
    Map<String,String> filtermap = new LinkedHashMap<String,String>();
        filtermap.put("/add","authc");
        filtermap.put("/update","authc");

        //授权过滤器
        //注意:当前授权拦截后,shiro会自动跳转到未授权页面
        filtermap.put("/add","perms[user:add]");
        filtermap.put("/update","perms[user:update]");
        //修改自动跳转页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");


        shiroFilterFactoryBean.setFilterChainDefinitionMap(filtermap);

    return shiroFilterFactoryBean ;
    }

    /**
     * 创建DefaultWebSecurityManager
     * @return
     */
    @Bean("securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("customerRealm") CustomerRealm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(realm);
        return securityManager ;
    }

    /**
     * 创建Realm
     * @return
     */
    @Bean("customerRealm")
    public CustomerRealm getRealm(){
        return new CustomerRealm();
    }

    /**
     * 配置ShiroDialect, 用于thymeleaf和shiro标签配合使用
     */

    @Bean
    public ShiroDialect  getShiroDialect(){
        return new ShiroDialect();
    }
}
